﻿#include "tcpServer.h"
#include "mainwindow.h"
extern intListener doorStatus;
TcpServer* TcpServer::Instance=0;

TcpServer* TcpServer::getInstance()
{
    if(Instance==0)
        Instance =new TcpServer();
    return Instance;
}

TcpServer::TcpServer(QObject *parent): QTcpServer(parent)
{
    tcpClient = TcpClient::getInstance();
}

//
TcpServer::~TcpServer()
{
}

void TcpServer::incomingConnection(qintptr socketDescriptor)
{
    MainWindow::oldExperimentStatus=MainWindow::experimentStatus.get();
    // 当有新连接时，创建一个QTcpSocket
    socket = new QTcpSocket(this);
    socket->setSocketDescriptor(socketDescriptor);
    MainWindow::tcpServerStatus.set(1);

    connect(socket, &QTcpSocket::readyRead, this, [=]() {
        QByteArray arr = socket->readAll();
        QString str;
        for(int c :arr)
        {
            if(c>=0)
            {
                str += QString(" %1").arg(c, 2, 16, QChar('0')).toUpper();
            }
            else
            {
                str += QString(" %1").arg(c+256, 2, 16, QChar('0')).toUpper();
            }
        }
        str= str.simplified();
        QStringList list=str.split(" ");

        if(list[6]=="01")//请求连接
        {
            QString serverData="62 00 00 3A 00 06 01 01 00 00 55 AA";
            QByteArray finalServerInfo=common->GetSendData(serverData);
            sendData(finalServerInfo);
            closeConnect();
        }
        else if(list[6]=="02")//打开仓门
        {
            doorStatus.set(1);
        }
        else if(list[6]=="03")//关闭仓门
        {
            doorStatus.set(0);
        }
        else if(list[6]=="04")//启动实验
        {
            QSqlDatabase db = dbHelper::openConnection();
            QSqlQuery query(db);

            db.transaction();

            MainWindow::experimentGuid = common->GetGuid();
            QString sql=QString("Delete from ExperimentInfo");
            query.exec(sql);
            query.clear();

            QDateTime dateTime = QDateTime::currentDateTime();

            QString expId= common->SixteenToTen(list[8]);
            QString consumableType=common->SixteenToTen(list[9]);

            QString experimentName=QString::number(dateTime.date().year())+GetDateString(dateTime.date().month())+GetDateString(dateTime.date().day())+GetDateString(dateTime.time().hour())+GetDateString(dateTime.time().minute())+GetDateString(dateTime.time().second());
            sql=QString("Insert into ExperimentInfo values ("
                        "'%1','%2','%3','','','','未启动','',(Select Name from ItemCode Where code='%4' and DicCode='6'),'')").arg(MainWindow::experimentGuid,experimentName,expId,consumableType);
            query.exec(sql);

            sql="Delete from SampleInfo";
            query.exec(sql);

            sql="Delete from SampleAccessInfo";
            query.exec(sql);

            for(int i=10;i<list.length()-4;i+=5){
                QString colNum="0";
                QString rowNum="0";

                QString pos= common->SixteenToTen(list[i]);
                QString type=common->SixteenToTen(list[i+1]);
                QString conc=common->SixteenToTen(list[i+2]+" "+list[i+3]);

                if(pos.toInt()%8==0){
                    rowNum="7";
                    colNum=QString::number(pos.toInt()/8-1);
                }else {
                    rowNum=QString::number(pos.toInt()%8-1);
                    colNum=QString::number(pos.toInt()/8);
                }

                QString sampleGuid=common->GetGuid();
                sql=QString("Insert into SampleInfo values('%1','%2','%3','%4','%5',(Select Name from ItemCode where Code='%6' and DicCode='2'),'%7','%8')").arg( sampleGuid,MainWindow::experimentGuid,colNum,rowNum,pos,type,QString::number(conc.toDouble()/1000),pos);
                query.exec(sql);

                QString access= common->SixteenToTwo(list[i+4]);
                if(access[0]=="1"){
                    sql=QString("Insert into SampleAccessInfo values('%1','%2','%3','')").arg( common->GetGuid(),sampleGuid,"FAM");
                    query.exec(sql);
                }
                if(access[1]=="1"){
                    sql=QString("Insert into SampleAccessInfo values('%1','%2','%3','')").arg( common->GetGuid(),sampleGuid,"VIC");
                    query.exec(sql);
                }
                if(access[2]=="1"){
                    sql=QString("Insert into SampleAccessInfo values('%1','%2','%3','')").arg( common->GetGuid(),sampleGuid,"ROX");
                    query.exec(sql);
                }
                if(access[3]=="1"){
                    sql=QString("Insert into SampleAccessInfo values('%1','%2','%3','')").arg( common->GetGuid(),sampleGuid,"CY5");
                    query.exec(sql);
                }
            }

            db.commit();

            MainWindow::startExperiment.set(1);
        }
        else if(list[6]=="05")//停止实验
        {
            MainWindow::startExperiment.set(2);
        }
        else if(list[6]=="06")//设备状态
        {
            if(MainWindow::experimentStatus.get()==1){
                QString serverData="62 00 00 3A 00 06 06 01 00 00 55 AA";
                QByteArray finalServerInfo=common->GetSendData(serverData);
                sendData(finalServerInfo);
                closeConnect();
            }
            else if(MainWindow::experimentStatus.get()==2){
                QString serverData="62 00 00 3A 00 06 06 03 00 00 55 AA";
                QByteArray finalServerInfo=common->GetSendData(serverData);
                sendData(finalServerInfo);
                closeConnect();
            }
            else if(MainWindow::experimentStatus.get()==3){
                QString serverData="62 00 00 3A 00 06 06 02 00 00 55 AA";
                QByteArray finalServerInfo=common->GetSendData(serverData);
                sendData(finalServerInfo);
                closeConnect();
            }
            else if(MainWindow::experimentStatus.get()==0){
                QString serverData="62 00 00 3A 00 06 06 04 00 00 55 AA";
                QByteArray finalServerInfo=common->GetSendData(serverData);
                sendData(finalServerInfo);
                closeConnect();
            }
        }
    });

    //    connect(socket, &QTcpSocket::disconnected, this, [=]() {
    //        MainWindow::tcpServerStatus.set(0);
    //    });
}

void TcpServer::closeConnect(){
    socket->disconnect();
}

void TcpServer::sendData(QByteArray array){
    socket->write(array);
}

QString TcpServer::GetDateString(int val){
    return QString::number(val).length()==2?QString::number(val): "0"+QString::number(val);
}
